<template>
  <el-dialog
    :model-value="modelValue"
    :title="isSubClass ? `添加子分类 - ${parentName}` : '添加分类'"
    width="500px"
    destroy-on-close
    @update:model-value="emit('update:modelValue', $event)"
    @closed="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="form"
    >
      <el-form-item v-if="isSubClass" label="父级分类">
        <el-input v-model="parentName" disabled placeholder="父级分类" />
      </el-form-item>

      <el-form-item label="分类名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入分类名称" />
      </el-form-item>

      <el-form-item v-if="isSubClass" label="分类图片" prop="image">
        <el-upload
          class="avatar-uploader"
          :action="uploadRef"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">建议尺寸：200x200px，支持jpg、png格式</div>
      </el-form-item>

      <el-form-item v-if="isSubClass" label="是否推荐" prop="is_featured">
        <el-switch
          v-model="form.is_featured"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { add } from "@/api/classify/classify";

const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  parentData: {
    type: Object,
    default: () => null
  }
});

//图片上传地址
const uploadRef = "http://127.0.0.1:2000/api/minio/uploadImages";

const emit = defineEmits(["update:modelValue", "success"]);

// 是否为子分类
const isSubClass = computed(() => !!props.parentData);
const parentName = computed(() => props.parentData?.name || "");

// 表单数据
const formRef = ref(null);
const submitting = ref(false);
const imageUrl = ref("");

const form = ref({
  name: "",
  image: "",
  parent_id: props.parentData?.id || 0,
  is_featured: 0
});

// 监听父级数据变化
watch(
  () => props.parentData,
  newVal => {
    form.value.parent_id = newVal?.id || 0;
  }
);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  image: [
    {
      required: isSubClass.value,
      message: "请上传分类图片",
      trigger: "change"
    }
  ]
};

// 图片上传前的验证
function beforeUpload(file) {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    ElMessage.error("只能上传 JPG 或 PNG 格式的图片!");
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
}

// 图片上传成功
function handleAvatarSuccess(res) {
  if (res.code === 200) {
    imageUrl.value = res.data;
    form.value.image = res.data;
  } else {
    ElMessage.error(res.message || "上传失败");
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();
    submitting.value = true;

    const res = await add(form.value);
    if (res.code === 200) {
      ElMessage.success("添加成功");
      emit("success");
      handleClose();
    } else {
      ElMessage.error(res.message || "添加失败");
    }
  } catch (error) {
    if (error?.message) {
      ElMessage.error(error.message);
    } else {
      ElMessage.error("添加失败");
    }
  } finally {
    submitting.value = false;
  }
}

// 关闭弹窗
function handleClose() {
  emit("update:modelValue", false);
  // 重置表单
  if (formRef.value) {
    formRef.value.resetFields();
  }
  imageUrl.value = "";
  form.value = {
    name: "",
    image: "",
    parent_id: props.parentData?.id || 0,
    is_featured: 0
  };
}
</script>

<style scoped>
.form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}

.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}
</style>
